<?php


	/**
	 * 返回JSON格式的数据
	 */
	function ajax_return($code,$msg,$data=array())
	{
		$arr = array(
				'code'=>$code,
				'msg'=>$msg,
				'data'=>$data
			);

		echo json_encode($arr);exit;
	}

	/**
	 * 判断数组中某个键值是否存在
	 */
	function check_in_array($arr,$key,$val)
	{
		foreach ($arr as $k => $v) {
			if($v[$key] == $val) {
				echo "checked";break;
			}
		}
	}

	/**
	 * 提取数组转换为Xeditable格式
	 * $data 需要提取的数据
	 * $key1 主键对应value
	 * $key2 其他键对应text
	 * 返回 处理后的JSON格式
	 */

	function xeditableItem($data,$key1=NULL,$key2=NULL)
	{
		$result = array();

		if(!empty($key1)&&!empty($key2))
		{
				foreach ($data as $key => $value) {
				$result[$key]['value'] = $data[$key][$key1];
				unset($data[$key][$key1]);
				$result[$key]['text'] = $data[$key][$key2];
				unset($data[$key][$key2]);
			}
		} else {
			$result = new arrayobject($data);
		}
		return str_replace('"', "&quot;", json_encode($result));
	}

	/**
	 * 检测是否有权限
	 */
	function has_permission($module_url,$action_url)
	{
		$CI =& get_instance();
		$CI->load->library('Auth');
		return $CI->auth->has_permission($module_url,$action_url);
	}

	function show_response($code,$msg,$data=array())
	{
		echo json_encode(array('code'=>$code,'msg'=>$msg,'data'=>$data));exit;
	}

	/**
	 * 设置消息
	 * @param string $status  状态
	 * @param strintg $message 消息内容
	 */
	function set_message($status,$msg)
	{
		if($status&&$msg) {
			$message = array('status'=>$status,'msg'=>$msg);
			return $message;
		}
		return NULL;
	}

    // 中文换行
    function mb_wordwrap($str, $width = 75, $break = "\n", $cut = false) {
        $lines = explode($break, $str);
        foreach ($lines as &$line) {
            $line = rtrim($line);
            if (mb_strlen($line) <= $width)
                continue;
            $words = explode(' ', $line);
            $line = '';
            $actual = '';
            foreach ($words as $word) {
                if (mb_strlen($actual.$word) <= $width)
                    $actual .= $word.' ';
                else {
                    if ($actual != '')
                        $line .= rtrim($actual).$break;
                    $actual = $word;
                    if ($cut) {
                        while (mb_strlen($actual) > $width) {
                            $line .= mb_substr($actual, 0, $width).$break;
                            $actual = mb_substr($actual, $width);
                        }
                    }
                    $actual .= ' ';
                }
            }
            $line .= trim($actual);
        }
        return implode($break, $lines);
    }
